<template>
  <div class="card">
    <div class="card-title">
      <el-icon><upload-filled /></el-icon>
      数据导入
    </div>
    <div class="upload-area" @dragover.prevent @drop="handleDrop">
      <el-upload
          drag
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          accept=".csv,.txt"
          class="upload-demo"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖放文件到此处或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip" style="margin-top: 20px;">
            支持CSV/TXT格式电磁信号数据
          </div>
        </template>
      </el-upload>
    </div>

    <div v-if="uploadProgress > 0" class="progress-status">
      <el-progress
          :text-inside="true"
          :stroke-width="20"
          :percentage="uploadProgress"
          status="success"
          striped
      />
      <p>{{ processStatus }}</p>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {ElIcon, ElNotification, ElProgress, ElUpload} from 'element-plus'
import {UploadFilled} from '@element-plus/icons-vue'

const emit = defineEmits(['file-uploaded'])

const uploadProgress = ref(0)
const processStatus = ref('')

const handleFileChange = (file) => {
  processFile(file.raw)
}

const handleDrop = (e) => {
  const files = e.dataTransfer.files
  if (files.length > 0) {
    processFile(files[0])
  }
}

const processFile = (file) => {
  if (!file) return

  if (file.size > 500 * 1024 * 1024) {
    ElNotification({
      title: '文件过大',
      message: `文件大小 ${(file.size/(1024 * 1024)).toFixed(2)}MB 超过系统处理能力`,
      type: 'warning',
      duration: 5000
    })
    return
  }

  const CHUNK_SIZE = 5 * 1024 * 1024 // 5MB chunks
  const chunks = Math.ceil(file.size / CHUNK_SIZE)
  let currentChunk = 0
  let results = []

  const processNextChunk = () => {
    if (currentChunk >= chunks) {
      // 所有分块处理完成
      emit('file-uploaded', results)
      return
    }

    const start = currentChunk * CHUNK_SIZE
    const end = Math.min(start + CHUNK_SIZE, file.size)
    const chunk = file.slice(start, end)

    const reader = new FileReader()
    reader.onload = (e) => {
      const text = e.target.result
      const chunkData = parseChunk(text)
      results = results.concat(chunkData)

      // 更新进度
      currentChunk++
      uploadProgress.value = Math.min(100, Math.round((currentChunk / chunks) * 100))
      processStatus.value = `处理中: ${currentChunk}/${chunks} 分块`

      // 使用setTimeout释放UI线程
      setTimeout(processNextChunk, 10)
    }

    reader.readAsText(chunk, 'gbk')
  }

  processStatus.value = '开始处理文件...'
  uploadProgress.value = 0
  processNextChunk()
}

const parseChunk = (text) => {
  const lines = text.split(/\r\n|\n/)
  return lines
      .filter(line => line.trim().length > 0 && !line.startsWith('时间'))
      .map(line => {
        const values = line.split(",")
        if (values.length < 8) return null

        return {
          time: parseFloat(values[0]),
          power: parseFloat(values[1]),
          DOA: parseFloat(values[2]),
          frequency: parseFloat(values[3]),
          bandwidth: parseFloat(values[4]),
          pulseWidth: parseFloat(values[5]),
          feature: parseInt(values[6]),
          SID: parseInt(values[7])
        }
      })
      .filter(item => item !== null)
}

</script>

<style scoped>
.card {
  background: rgba(19, 25, 60, 0.8);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 40, 0.5);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(64, 158, 255, 0.1);
  transition: all 0.3s ease;
}

.card:hover {
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-5px);
}

.card-title {
  font-size: 1.3rem;
  color: #4facfe;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(100, 120, 230, 0.2);
  display: flex;
  align-items: center;
}

.card-title i {
  font-size: 1.5rem;
  margin-right: 10px;
}

.upload-area {
  border: 2px dashed #4579ff;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(11, 20, 55, 0.4);
}

.upload-area:hover {
  background: rgba(15, 35, 90, 0.4);
}

.progress-status {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 25px;
  padding: 0 30px;
}
</style>